﻿using System.Reflection;

namespace AntdUI_HamburgerMenuTabs
{
    public static class ControlExtentions
    {
        public static Control? Clone(this Control original)
        {
            if (original == null) return null;

            Control? clone;

            try
            {
                // 根据原控件类型创建新实例
                clone = (Control?)Activator.CreateInstance(original.GetType());
            }
            catch
            {
                return null;
            }

            // 复制属性
            foreach (PropertyInfo prop in original.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (!prop.CanWrite)
                    continue;

                if (prop.Name == "Handle" || prop.Name == "ClientRectangle" ||
                    prop.Name == "Bounds" || prop.Name == "Parent")
                    continue;

                try
                {
                    object? value = prop.GetValue(original, null);
                    prop.SetValue(clone, value, null);
                }
                catch
                {
                    // 忽略无法复制的属性
                }
            }

            // 克隆子控件
            foreach (Control child in original.Controls)
            {
                Control? childClone = Clone(child);
                clone?.Controls.Add(childClone);
            }

            return clone;
        }
    }
}